package com.titaniume.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: juc
 * @Package: com.titaniume.queue
 * @ClassName: BlockingQueueDemo
 * @Author: huangrenfei
 * @Description: 阻塞队列案例
 * @Date: 2021/11/24 16:32
 * @Version: 1.0
 */
public class BlockingQueueDemo {

    public static void main(String[] args)  throws  Exception {

        ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

        //第一组 抛出异常

//        System.out.println(blockingQueue.add("a"));
//        System.out.println(blockingQueue.add("b"));
//        System.out.println(blockingQueue.add("c"));
//        System.out.println(blockingQueue.add("d")); //Exception in thread "main" java.lang.IllegalStateException: Queue full

//        System.out.println(blockingQueue.remove());
//        System.out.println(blockingQueue.remove());
//        System.out.println(blockingQueue.remove());
//        System.out.println(blockingQueue.remove()); //Exception in thread "main" java.util.NoSuchElementException

        //第二组 特殊值
//        System.out.println(blockingQueue.offer("a"));
//        System.out.println(blockingQueue.offer("b"));
//        System.out.println(blockingQueue.offer("c"));
//        System.out.println(blockingQueue.offer("d")); //false
//
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());
//        System.out.println(blockingQueue.poll());  //null


        //第三组 阻塞
//        blockingQueue.put("a");
//        blockingQueue.put("b");
//        blockingQueue.put("c");
////        blockingQueue.put("d"); //到了c已经满了，继续添加到d 程序会阻塞
//
//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());
//        System.out.println(blockingQueue.take());  // 队列总没有第四个元素，如果去取空的元素也会阻塞


        //第四组 超时
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        System.out.println(blockingQueue.offer("c"));
        System.out.println(blockingQueue.offer("d",3L, TimeUnit.SECONDS));  //设置超时时间，3秒后结束程序

    }
}
